using System;
using System.Collections.Generic;
using UnityEngine;

namespace GamePlay.Framework.Events
{
    /// <summary>
    /// 基于C#原生事件系统的事件管理器
    /// </summary>
    public class EventManager
    {
        #region 单例实现
        
        private static EventManager _instance;
        
        public static EventManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new EventManager();
                }
                return _instance;
            }
        }
        
        private EventManager()
        {
            // 初始化
            _eventHandlers = new Dictionary<Type, Delegate>();
            _debugMode = false;
        }
        
        #endregion
        
        #region 字段和属性
        
        // 存储所有事件处理器
        private Dictionary<Type, Delegate> _eventHandlers;
        
        // 是否打印调试日志
        private bool _debugMode = false;
        
        /// <summary>
        /// 设置或获取调试模式
        /// </summary>
        public bool DebugMode
        {
            get { return _debugMode; }
            set { _debugMode = value; }
        }
        
        #endregion
        
        #region 事件管理方法
        
        /// <summary>
        /// 为指定事件类型注册事件处理器
        /// </summary>
        /// <typeparam name="T">事件类型</typeparam>
        /// <param name="handler">事件处理方法</param>
        public void RegisterHandler<T>(EventHandler<T> handler) where T : EventArgs
        {
            Type eventType = typeof(T);
            
            if (_debugMode)
            {
                Debug.Log($"[EventManager] 注册事件处理器: {eventType.Name}, 方法: {handler.Method.Name}");
            }
            
            // 使用 Delegate.Combine 来添加新的处理器
            _eventHandlers[eventType] = Delegate.Combine(
                _eventHandlers.TryGetValue(eventType, out Delegate existingHandler) ? existingHandler : null, 
                handler);
        }
        
        /// <summary>
        /// 取消指定事件类型的事件处理器注册
        /// </summary>
        /// <typeparam name="T">事件类型</typeparam>
        /// <param name="handler">事件处理方法</param>
        public void UnregisterHandler<T>(EventHandler<T> handler) where T : EventArgs
        {
            Type eventType = typeof(T);
            
            if (_eventHandlers.TryGetValue(eventType, out Delegate existingHandler))
            {
                Delegate newDelegate = Delegate.Remove(existingHandler, handler);
                
                if (newDelegate != null)
                {
                    _eventHandlers[eventType] = newDelegate;
                }
                else
                {
                    _eventHandlers.Remove(eventType);
                }
                
                if (_debugMode)
                {
                    Debug.Log($"[EventManager] 已取消注册事件处理器: {eventType.Name}, 方法: {handler.Method.Name}");
                }
            }
        }
        
        /// <summary>
        /// 触发指定类型的事件
        /// </summary>
        /// <typeparam name="T">事件类型</typeparam>
        /// <param name="sender">事件发送者</param>
        /// <param name="eventArgs">事件参数</param>
        public void RaiseEvent<T>(object sender, T eventArgs) where T : EventArgs
        {
            Type eventType = eventArgs.GetType();
            
            if (_eventHandlers.TryGetValue(eventType, out Delegate handler))
            {
                // 获取所有订阅此事件的处理器
                Delegate[] handlers = handler.GetInvocationList();
                
                if (_debugMode)
                {
                    Debug.Log($"[EventManager] 触发事件: {eventType.Name}, 处理器数量: {handlers.Length}");
                }
                
                // 调用每个处理器
                foreach (Delegate del in handlers)
                {
                    try
                    {
                        
                        del.DynamicInvoke(sender, eventArgs);
                        
                    }
                    catch (Exception ex)
                    {
                        Debug.LogError($"[EventManager] 处理事件时出错:{eventType} {ex.Message}");
                    }
                }
            }
            else if (_debugMode)
            {
                Debug.Log($"[EventManager] 没有处理器注册事件: {eventType.Name}");
            }
        }
        
        /// <summary>
        /// 是否有处理器订阅了指定事件类型
        /// </summary>
        /// <typeparam name="T">事件类型</typeparam>
        /// <returns>如果有处理器订阅则返回true，否则返回false</returns>
        public bool HasHandlers<T>() where T : EventArgs
        {
            return _eventHandlers.ContainsKey(typeof(T));
        }
        
        /// <summary>
        /// 清除所有事件订阅
        /// </summary>
        public void ClearAllHandlers()
        {
            _eventHandlers.Clear();
            
            if (_debugMode)
            {
                Debug.Log("[EventManager] 已清除所有事件订阅");
            }
        }
        
        /// <summary>
        /// 清除特定类型的所有事件订阅
        /// </summary>
        /// <typeparam name="T">事件类型</typeparam>
        public void ClearHandlers<T>() where T : EventArgs
        {
            Type eventType = typeof(T);
            
            if (_eventHandlers.Remove(eventType) && _debugMode)
            {
                Debug.Log($"[EventManager] 已清除事件类型的所有订阅: {eventType.Name}");
            }
        }
        
        /// <summary>
        /// 获取特定事件类型的处理器数量
        /// </summary>
        /// <typeparam name="T">事件类型</typeparam>
        /// <returns>处理器数量</returns>
        public int GetHandlerCount<T>() where T : EventArgs
        {
            if (_eventHandlers.TryGetValue(typeof(T), out Delegate handler))
            {
                return handler.GetInvocationList().Length;
            }
            return 0;
        }
        
        #endregion
        
        #region 对象生命周期绑定
        
        /// <summary>
        /// 为特定对象注册事件处理器，在对象销毁时自动取消注册
        /// </summary>
        /// <typeparam name="T">事件类型</typeparam>
        /// <param name="target">目标游戏对象</param>
        /// <param name="handler">事件处理方法</param>
        public void RegisterHandlerForObject<T>(GameObject target, EventHandler<T> handler) where T : EventArgs
        {
            if (target == null)
            {
                Debug.LogError("[EventManager] 无法为空对象注册事件处理器");
                return;
            }
            
            // 先正常注册事件处理器
            RegisterHandler<T>(handler);
            
            // 添加自动取消注册的组件
            EventTracker tracker = target.GetComponent<EventTracker>();
            if (tracker == null)
            {
                tracker = target.AddComponent<EventTracker>();
            }
            
            // 在对象销毁时取消注册
            tracker.AddHandler(() => UnregisterHandler<T>(handler));
            
            if (_debugMode)
            {
                Debug.Log($"[EventManager] 已为对象 {target.name} 注册事件处理器: {typeof(T).Name}");
            }
        }
        
        #endregion
    }
    
    /// <summary>
    /// 用于跟踪事件订阅并在对象销毁时自动取消订阅
    /// </summary>
    public class EventTracker : MonoBehaviour
    {
        private List<Action> _unsubscribeActions = new List<Action>();
        
        /// <summary>
        /// 添加一个取消订阅的操作
        /// </summary>
        /// <param name="unsubscribeAction">取消订阅的操作</param>
        public void AddHandler(Action unsubscribeAction)
        {
            _unsubscribeActions.Add(unsubscribeAction);
        }
        
        private void OnDestroy()
        {
            foreach (Action action in _unsubscribeActions)
            {
                try
                {
                    action?.Invoke();
                }
                catch (Exception ex)
                {
                    Debug.LogError($"[EventTracker] 取消订阅事件时出错: {ex.Message}");
                }
            }
            _unsubscribeActions.Clear();
        }
    }
}